// business js
var access_token = '';
var refresh_token = '';
var expires_in = '';
var local_time = '';
var selectLang = '';

app
// general rest service call, 'urladdress' must in ended with ?
    .service('RESTService', function ($q, $http, $state, $timeout, $window, $translate, $rootScope, Oauth2, Scopes, AuthService, RS, toaster) {
        var restservice = {};
        // param: urladdress - url of rest

        restservice.pop = function (infoType, intoTitle, intoText, timeout) {
            if (timeout == null) {
                timeout = 5000;
            }
            toaster.pop(infoType, intoTitle, intoText, timeout);
            return toaster.toast.id;
        };
        restservice.clear = function (id) {
            // toaster.clear();
            toaster.close(id);
        };

        restservice.getResponse = function (urladdress, returnRes) {
            // alert("get--"+urladdress);
            return restservice.processResponse("get", urladdress, null, returnRes);
        }

        restservice.postResponse = function (urladdress, data, returnRes) {
            // alert("post--"+urladdress);
            return restservice.processResponse("post", urladdress, data, returnRes);
        }

        restservice.processResponse = function (method, urladdress, data, returnRes) {
            var rest_data = [];
            var refresh_token = '';
            access_token = AuthService.loadData("_access_token");
            refresh_token = AuthService.loadData("_refresh_token");
            expires_in = AuthService.loadData("_expires_in");
            local_time = AuthService.loadData("_local_time");

            if (access_token == "" || expires_in == "" || local_time == "") {
                AuthService.logout();
                return;
            }

            var funcName = urladdress.split('\/')[2];
            urladdress = AuthService.getRsContext() + urladdress;

            var curr_time = (new Date()).getTime();
            if (curr_time - local_time < expires_in * 1000) {
                return restservice.processHttp(method, urladdress + "&access_token=" + access_token, data, funcName).then(function (data1) {
                    if (returnRes) {
                        rest_data = data1;
                    } else {
                        angular.forEach(data1.data, function (value, key) {
                            rest_data[key] = value;
                            //console.log(key + ': ' + value);
                        });
                    }
                    return rest_data;
                }, function (data2) {
                    restservice.pop("error", "error", "Network error!");
                });
                // return rest_data;
            } else {
                var refresh_url = Oauth2.protocol + Oauth2.server + Oauth2.port + Oauth2.context + Oauth2.tokenUrl
                    + "?" + Oauth2.clientId + "&" + Oauth2.clientSecret + "&grant_type=refresh_token&refresh_token=" + refresh_token;

                restservice.processHttp("get", refresh_url, data, funcName).then(function (data3) {
                    access_token = data3.access_token;
                    expires_in = data3.expires_in;
                    local_time = (new Date()).getTime();

                    AuthService.storeData("_access_token", access_token);
                    AuthService.storeData("_refresh_token", refresh_token);
                    AuthService.storeData("_expires_in", expires_in);
                    AuthService.storeData("_local_time", local_time);


                    var logininfo = Scopes.get('login_info');
                    Scopes.store('login_info', logininfo);

                    return restservice.processHttp(method, urladdress + "&access_token=" + access_token, data, funcName).then(function (data5) {
                        if (returnRes) {
                            rest_data = data5;
                        } else {
                            angular.forEach(data5.data, function (value, key) {
                                rest_data[key] = value;
                                //console.log(key + ': ' + value);
                            });
                        }
                        return rest_data;
                    }, function (data6) {
                        restservice.pop("error", "error", "Network error!");
                    })
                }, function (data4) {
                    // AuthService.logout();
                    // $state.go('login');
                    var dataError = data4.error;
                    if (dataError == "invalid_grant") {
                        AuthService.logout();
                        $state.go('access.login');
                    }
                    else {
                        restservice.pop("error", "error", "Network error!");
                    }
                });

                // return rest_data;
            }
        };

        restservice.processHttp = function (method, urladdress, data, funcName) {
            if (method == "post") {
                return restservice.postHttp(urladdress, data, funcName);
            }
            else {
                return restservice.getHttp(urladdress, funcName);
            }
        }

        restservice.getHttp = function (urladdress, funcName) {
            //console.log('RESTService getData urladdress=', urladdress);
            // wait
            var waitkey = urladdress.substr(0, urladdress.indexOf("?"));
            waitkey = waitkey.substr(waitkey.indexOf("/rest/"));
            var waitMsg = $translate.instant("rest.wait." + waitkey);
            var waitId = 0;
            if (waitMsg != "rest.wait." + waitkey) {
                waitId = restservice.pop("wait", "", "  " + waitMsg, 0);
            }

            var deferred = $q.defer();
            $http({
                method: "GET",
                url: urladdress
            }).success(function (data, status, headers, config) {
                restservice.clear(waitId);
                console.log('RESTService successfully getData=', urladdress, data);
                deferred.resolve(data);
                if (data.code != null) {
                    var code = data.code;

                    if (code != 0) {
                        var keyMsg = "rest.error." + funcName + ".code" + code;
                        var keyTitle = "rest.error." + funcName + ".title";
                        var errMsg = $translate.instant(keyMsg);

                        if (code == -1 && (errMsg == keyMsg)) {
                            errMsg = $translate.instant("rest.error.exception");
                        }

                        var errTitle = $translate.instant("rest.error." + funcName + ".title");
                        if (errTitle == null || errTitle == "" || errTitle == keyTitle) {
                            errTitle = $translate.instant("rest.error.title");
                        }
                        if (code > 0) {
                            var errCode = $translate.instant("rest.error.code");
                            errTitle = errTitle + " (" + errCode + ": " + code + ")";
                        }

                        // get errMsg from data.message
                        if (errMsg == null || errMsg == "" || errMsg == keyMsg) {
                            if (selectLang == "English") {
                                errMsg = data.enMessage;
                            }
                            if (errMsg == null || errMsg == "" || errMsg == keyMsg) {
                                errMsg = data.message;
                            }
                        }

                        // get type, default is error, you can set 'warning' in language file
                        var errType = "error";
                        errType = $translate.instant("rest.error.type_" + code);
                        if (errType == null || errType == "") {
                            errType = "error";
                        }
                        // warning, blank title
                        if (errType == "warning") {
                            errTitle = "";
                        }
                        if (errMsg != null && errMsg != "") {
                            restservice.pop(errType, errTitle, errMsg);
                        }
                    }
                    else {
                        // success
                        var successDebug = $translate.instant("rest.success.debug");
                        var key = urladdress.substr(0, urladdress.indexOf("?"));
                        key = key.substr(key.indexOf("/rest/"));
                        var successTitle = $translate.instant("rest.success." + key + "_title");
                        if (successTitle == "rest.success." + key + "_title") {
                            successTitle = "";
                        }
                        var successMsg = $translate.instant("rest.success." + key);
                        if (successMsg != "rest.success." + key) {
                            restservice.pop("success", successTitle, successMsg);
                        }
                        if (successDebug == "true") {
                            restservice.pop("success", "", "key: " + key);
                        }
                    }
                }
            }).error(function (data, status, headers, config) {
                restservice.clear();
                //console.log('RESTService error getData=', data);
                deferred.reject(data);
            });
            return (deferred.promise);
        };

        restservice.postHttp = function (urladdress, data, funcName) {
            // wait
            var waitkey = urladdress.substr(0, urladdress.indexOf("?"));
            waitkey = waitkey.substr(waitkey.indexOf("/rest/"));
            var waitMsg = $translate.instant("rest.wait." + waitkey);
            var waitId = 0;
            if (waitMsg != "rest.wait." + waitkey) {
                waitId = restservice.pop("wait", "", "  " + waitMsg, 0);
            }

            var transFn = function (data) {
                return $.param(data);
            };
            var postCfg = {
                headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                transformRequest: transFn
            };

            var deferred = $q.defer();

            $http.post(urladdress,
                data,
                postCfg
            ).success(function (data, status, headers, config) {
                restservice.clear(waitId);
                console.log('RESTService successfully postData=', urladdress, data);
                deferred.resolve(data);
                if (data.code != null) {
                    var code = data.code;

                    if (code != 0) {
                        var keyMsg = "rest.error." + funcName + ".code" + code;
                        var keyTitle = "rest.error." + funcName + ".title";
                        var errMsg = $translate.instant(keyMsg);

                        if (code == -1 && (errMsg == keyMsg)) {
                            errMsg = $translate.instant("rest.error.exception");
                        }

                        var errTitle = $translate.instant("rest.error." + funcName + ".title");
                        if (errTitle == null || errTitle == "" || errTitle == keyTitle) {
                            errTitle = $translate.instant("rest.error.title");
                        }
                        if (code > 0) {
                            var errCode = $translate.instant("rest.error.code");
                            errTitle = errTitle + " (" + errCode + ": " + code + ")";
                        }

                        // get errMsg from data.message
                        if (errMsg == null || errMsg == "" || errMsg == keyMsg) {
                            if (selectLang == "English") {
                                errMsg = data.enMessage;
                            }
                            if (errMsg == null || errMsg == "" || errMsg == keyMsg) {
                                errMsg = data.message;
                            }
                        }

                        // get type, default is error, you can set 'warning' in language file
                        var errType = "error";
                        errType = $translate.instant("rest.error.type_" + code);
                        if (errType == null || errType == "") {
                            errType = "error";
                        }
                        // warning, blank title
                        if (errType == "warning") {
                            errTitle = "";
                        }
                        if (errMsg != null && errMsg != "") {
                            restservice.pop(errType, errTitle, errMsg);
                        }
                    }
                    else {
                        // success
                        var successDebug = $translate.instant("rest.success.debug");
                        var key = urladdress.substr(0, urladdress.indexOf("?"));
                        key = key.substr(key.indexOf("/rest/"));
                        var successTitle = $translate.instant("rest.success." + key + "_title");
                        if (successTitle == "rest.success." + key + "_title") {
                            successTitle = "";
                        }
                        var successMsg = $translate.instant("rest.success." + key);
                        if (successMsg != "rest.success." + key) {
                            restservice.pop("success", successTitle, successMsg);
                        }
                        if (successDebug == "true") {
                            restservice.pop("success", "", "key: " + key);
                        }
                    }
                }
            }).error(function (data, status, headers, config) {
                restservice.clear();
                //console.log('RESTService error getData=', data);
                deferred.reject(data);
            });
            return (deferred.promise);
        };

        restservice.getAccess_Token = function () {
            access_token = '';

            access_token = AuthService.loadData("_access_token");
            refresh_token = AuthService.loadData("_refresh_token");
            expires_in = AuthService.loadData("_expires_in");
            local_time = AuthService.loadData("_local_time");

            var curr_time = (new Date()).getTime();
            if (local_time == null || local_time == '' || expires_in == null || expires_in == '') {
                console.log("REST.js return BLANK access_token because local_time and expires_in are blank!");
                return '';
            } else {
                if (curr_time - local_time > expires_in * 1000) {
                    console.log("REST.js return BLANK access_token because local_time and expires_in are expired!");
                    return '';
                }
            }
            return access_token;
        };

        restservice.setLang = function (lang) {
            selectLang = lang;
        };

        return restservice;
    })

    /**
     * global scope stored:
     * login_info (from controllers.js)
     */
    .factory("Scopes", function () {
        var store = {};
        return {
            store: function (key, value) {
                // console.log('Scopes store key =',key,',value=',valuetostore);
                store[key] = value;
            },
            get: function (key) {
                // console.log('Scopes get key =',key,',value=',store[key]);
                return store[key];
            },
            delete: function (key) {
                delete store[key];
            }
        };

    });